#define WIN32_LEAN_AND_MEAN
#include <windows.h>

#include "GMutex.h"
#include "GError.h"

namespace GThread
{
	// Description: Creates a mutex with given parameters
	// Return: True is successfull, false otherwise.
	// Notes: If a mutex is created with same name before, the created mutex will be a referance to the previous one
	// -----------------------------------------------------
	bool GMutex::Create(bool StartAcquired, const char* Name)
	{
		if (IsCreated())
		{
			return false;
		}

		Mutex = CreateMutex(NULL, StartAcquired, Name);
		if (Mutex == NULL)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		this->Name = Name == NULL ? "" : Name;

		return true;
	}

	// Description: Releases the handle.
	// Return:
	// Notes: Does not release the actual mutex object until referance count of the mutex drops to zero.
	// -----------------------------------------------------
	void GMutex::Release()
	{
		if (!IsCreated())
		{
			return;
		}
	
		Name = "";

		CloseHandle(Mutex);
		Mutex = NULL;
	}

	// Description: Frees the mutex.
	// Return: true if successfull, false otherwise
	// Notes: Mutex must be created.
	// -----------------------------------------------------
	bool GMutex::Free()
	{
		GUtil::GError::DebugCheck(!IsCreated(), "Mutex is not created.");

		BOOL Result = ReleaseMutex(Mutex);
		if (Result == 0)
		{
			GUtil::GError::Error(GUtil::GErrorMessageWin32(GetLastError()));
			return false;
		}

		return true;
	}

}